package com.gastudio.Basic;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * Created by 余艾龙 on 2017/6/20.
 */
public class MinaClient {
    private static String HOST  ="127.0.0.1";
    private static int PORT =8090;
    public static void main(String[] args) {
        IoSession session=null;
        IoConnector connector=new NioSocketConnector();
        //设置超时时间
        connector.setConnectTimeoutMillis(3000);
        //设置过滤器
        connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(
                new TextLineCodecFactory(
                        Charset.forName("UTF-8"),
                        LineDelimiter.WINDOWS.getValue(),
                        LineDelimiter.WINDOWS.getValue()
                )
        ));
        connector.getFilterChain().addFirst("filter",new MyClientFilter());
        connector.setHandler(new MyClientHandler("你好!\r\n大家好!"));
        //请求连接
        ConnectFuture future= connector.connect(new InetSocketAddress(HOST,PORT));
        //等待连接完成
        future.awaitUninterruptibly();
        //连接完成后获取会话
        session=future.getSession();
        session.write("你好！");
        session.getCloseFuture().awaitUninterruptibly();//等待关闭连接
        connector.dispose();
    }
}
